using System.Collections.Generic;
using System;

public class Pool<T>
{
	private readonly List<T> items = new List<T>();
	private readonly Stack<T> freeItems = new Stack<T>();

	private readonly Func<T> createItemAction;

	public Pool(Func<T> createItemAction)
	{
		this.createItemAction = createItemAction;
	}

	public void FlagFreeItem(T item)
	{
		freeItems.Push(item);
	}

	public T GetFreeItem()
	{
		if (freeItems.Count == 0)
		{
			T item = createItemAction();
			items.Add(item);

			return item;
		}

		return freeItems.Pop();
	}

	public List<T> Items
	{
		get { return items; }
	}

	public void Clear()
	{
		items.Clear();
		freeItems.Clear();
	}
}